<template>
    <div class="app-container">
        <div class="top-total">
            <div class="item">
                <h3>总消耗</h3>
                <p>{{tableData.totalCost?tableData.totalCost:0}}</p>
            </div>
            <div class="item">
                <h3>总现金消耗</h3>
                <p>{{tableData.totalRealCost?tableData.totalRealCost:0}}</p>
            </div>
            <div class="item">
                <h3>归因回收</h3>
                <p>{{tableData.monitorIncome?tableData.monitorIncome:0}}&nbsp;&nbsp;ROI({{tableData.totalCost?(tableData.monitorIncome/tableData.totalCost*100).toFixed(2):0}}%)</p>
            </div>
            <div class="item" v-if="queryParams.type==2">
                <h3>总回收</h3>
                <p>{{tableData.totalIncome?tableData.totalIncome:0}}&nbsp;&nbsp;ROI({{tableData.totalRealCost?(tableData.totalIncome/tableData.totalRealCost*100).toFixed(2):0}}%)</p>
            </div>
        </div>
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" size="mini">
            <el-query-row :label="'维度'" :labelWidth="80" class="table-button-group">
                <el-col :span="8">
                    <el-button-group :autofocus="true">
                        <el-button size="mini" v-for="(item, index) in dataDimensionList" :key="item + index"
                            :disabled="item.disable" :class="[item.value === queryParams.type ? 'active' : '']"
                            @click="_changeParams('type', item.value)">
                            {{ item.name }}
                        </el-button>
                    </el-button-group>
                </el-col>
                <el-col :span="16">
                    <el-form-item label="时间范围" prop="dateRange">
                        <el-date-picker
                        v-model="queryParams.dateRange"
                        style="margin-left:20px;"
                        value-format="yyyy-MM-dd HH"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"
                        :default-value="[new Date(), new Date()]"
                        :default-time="['00:00:00']"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-query-row>
            <el-row>
                <el-col :span="12">
                    <el-query-row :label="'消耗范围'" :labelWidth="80" class="table-button-group">
                        <el-col :span="11">
                            <el-form-item prop="minCost">
                                <el-input placeholder="请输入消耗" v-model="queryParams.minCost" class="input-with-select">
                                    <el-select v-model="queryParams.minCostOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col class="line" style="width: 15px;">-</el-col>
                        <el-col :span="11">
                            <el-form-item prop="maxCost">
                                <el-input placeholder="请输入消耗" v-model="queryParams.maxCost" class="input-with-select">
                                    <el-select v-model="queryParams.maxCostOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-query-row>
                </el-col>
                <el-col :span="12">
                    <el-query-row :label="'roi范围'" :labelWidth="80" class="table-button-group">
                        <el-col :span="11">
                            <el-form-item prop="minRoi">
                                <el-input placeholder="请输入roi" v-model="queryParams.minRoi" class="input-with-select">
                                    <el-select v-model="queryParams.minRoiOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col class="line" style="width: 15px;">-</el-col>
                        <el-col :span="11">
                            <el-form-item prop="maxRoi">
                                <el-input placeholder="请输入roi" v-model="queryParams.maxRoi" class="input-with-select">
                                    <el-select v-model="queryParams.maxRoiOperator" slot="prepend" placeholder="条件"
                                        clearable style="width: 100px;">
                                        <el-option v-for="item in indexSymbol" :key="item.val" :label="item.name"
                                            :value="item.val">
                                        </el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-query-row>
                </el-col>
            </el-row>
            <el-query-row :label="'筛选项'" :labelWidth="80">
                <el-col :span="4" class="mb10">
                    <el-form-item prop="pkg">
                        <el-select v-model="queryParams.pkg" placeholder="应用" style="width: 100%;"
                            collapse-tags filterable clearable @change="_productChange">
                            <el-option v-for="(item, index) in productList" :key="item + index" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10">
                    <el-form-item prop="agentCode">
                        <el-select v-model="queryParams.agentCode" placeholder="代理" style="width: 100%;" @change="_agentChange" filterable clearable>
                            <el-option
                            v-for="item in dict.type.ACCOUNT_AGENT"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10">
                    <el-form-item prop="accountId">
                        <el-select v-model="queryParams.accountId" placeholder="账户" style="width: 100%;" :filter-method="accountFilter" multiple
                            collapse-tags filterable clearable>
                            <el-option v-for="(item, index) in filteredAccountOptions" :key="item.accountId" :label="item.accountName"
                                :value="item.accountId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10" v-if="queryParams.type==4">
                    <el-form-item prop="planId">
                      <el-select v-model="queryParams.planId" placeholder="计划" style="width: 100%;" :filter-method="placeFilter" multiple
                          collapse-tags filterable clearable>
                          <el-option v-for="(item, index) in filteredPlaceOptions" :key="item.dimensionId" :label="item.dimensionName"
                              :value="item.dimensionId" />
                      </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10" v-if="queryParams.type==5">
                    <el-form-item prop="unitId">
                        <el-select v-model="queryParams.unitId" placeholder="任务" style="width: 100%;" :filter-method="placeFilter" multiple
                            collapse-tags filterable clearable>
                            <el-option v-for="(item, index) in filteredPlaceOptions" :key="item.dimensionId" :label="item.dimensionName"
                                :value="item.dimensionId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10" v-if="queryParams.type==6">
                    <el-form-item prop="creativeId" clearable>
                        <el-select v-model="queryParams.creativeId" placeholder="创意" style="width: 100%;" :filter-method="placeFilter" multiple
                            collapse-tags filterable >
                            <el-option v-for="item in filteredPlaceOptions" :key="item.dimensionId" :label="item.dimensionName"
                                :value="item.dimensionId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" class="mb10">
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                        <el-button type="info" :loading="reportTaskLoading" @click="reportTask">拉取报表数据</el-button>
                    </el-form-item>
                </el-col>
            </el-query-row>
        </el-form>

        <el-table v-loading="loading" :data="tableDataList" :height="tableHeight" :key="queryParams.type"
            :default-sort="defaultSort" @sort-change="_changeSort">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="日期" align="center" prop="acdate" width="90" sortable="custom">
              <template #default="scope">
                {{scope.row['acdate']}}
              </template>
            </el-table-column>
            <el-table-column label="应用" align="center" width="200">
              <template #default="scope">
                  <div>{{ scope.row['appName'] }}</div>
                  <div v-if="queryParams.type !== '3'&&queryParams.type !== '2'">{{ scope.row['accountId'] }}</div>
                  <div v-if="queryParams.type !== '3'&&queryParams.type !== '2'">{{ scope.row['accountName'] }}</div>
                  <div v-if="queryParams.type !== '3'&&queryParams.type !== '2'">{{ scope.row['agentName'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="账户" align="center" width="200" v-if="queryParams.type == '3'">
              <template #default="scope">
                  <div>{{ scope.row['accountId'] }}</div>
                  <div>{{ scope.row['accountName'] }}</div>
                  <div>{{ scope.row['agentName'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="计划" align="center" width="200" v-if="queryParams.type == '4' || queryParams.type == '5' || queryParams.type == '7'">
              <template #default="scope">
                  <div>{{ scope.row['planId'] }}</div>
                  <div>{{ scope.row['planName'] }}</div>
                  <div>目标:{{ scope.row['convertTypes'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="任务" align="center" width="200" v-if="queryParams.type == '5'">
              <template #default="scope">
                  <div>{{ scope.row['adgroupId'] }}</div>
                  <div>{{ scope.row['adgroupName'] }}</div>
                  <div>投放策略:{{ scope.row['strategy'] }}</div>
                  <div>投放周期:{{ scope.row['launchBeginDate'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="创意" align="center" width="200" v-if="queryParams.type == '6'">
              <template #default="scope">
                  <div>{{ scope.row['creativeId'] }}</div>
                  <div>{{ scope.row['creativeName'] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="渠道" align="center" width="70">
              <template #default="scope">
                  <dict-tag :options="dict.type.sys_channel" :value="scope.row['channel']"/>
              </template>
            </el-table-column>
            <el-table-column label="投放状态" align="center" width="100" prop="status"/>
            <el-table-column label="账户数" align="center" prop="appCount" width="100" v-if="queryParams.type=='2'"/>
            <el-table-column label="预算" align="center" width="150" v-if="queryParams.type=='3'||queryParams.type=='4'">
                <template #default="scope">
                    <div>{{ scope.row['budget'] }}</div>
                    <div><el-progress :percentage="+(scope.row.cost / scope.row.budget * 100).toFixed(0)"/></div>
                    <div v-if="queryParams.type=='3'">余额：{{ scope.row['offer'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="出价" align="center" v-if="queryParams.type=='4' || queryParams.type=='5'" width="150">
                <template #default="scope">
                    <div>转化成本(Z)：{{ scope.row['zconvertCost'] }}</div>
                    <div>转化成本(J)：{{ scope.row['jconvertCost'] }}</div>
                    <div>出价：{{ scope.row['offer'] }} <el-button size="mini" type="text" @click="handleOffer(scope.row)">修改</el-button></div>
                    <div>计费比(z)： {{ scope.row['zconvertRatio'] }}</div>
                    <div>计费比(j)： {{ scope.row['jconvertRatio'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="投产" align="center" prop="cost" width="200" sortable="custom">
                <template #default="scope">
                  <div>账面消耗：{{ scope.row['cost'] }}</div>
                  <div>回收：{{ scope.row['income'] }}</div>
                  <div>账面ROI：{{ scope.row['roi'] }}</div>
                  <div>赔付（预估）：{{ scope.row['compensation'] }}</div>
                  <div>利润（预估）：{{ scope.row['profit'] }}</div>
                  <div>赔反Roi（预估）：{{ scope.row['compensationRoi'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="总投产" align="center" prop="cost" width="200">
                <template #default="scope">
                  <div v-if="scope.row['totalProductionData']">
                    <div>账面消耗：{{ scope.row['totalProductionData']['cost'].toFixed(2) }}</div>
                    <div>回收：{{ scope.row['totalProductionData']['income'] }}</div>
                    <div>账面ROI：{{ scope.row['totalProductionData']['roi'] }}</div>
                    <div>总赔付（预估）：{{ scope.row['totalProductionData']['compensation'].toFixed(2) }}</div>
                    <div>总利润（预估）：{{ scope.row['totalProductionData']['profit'] }}</div>
                    <div>赔反Roi（预估）：{{ scope.row['totalProductionData']['compensationRoi'] }}</div>
                  </div>
                  <div v-else>无</div>
                </template>
            </el-table-column>
            <el-table-column label="投放赔付周期T1" align="center" prop="cost" width="250">
                <template #default="scope">
                  <div v-if="scope.row['t1ProductionData']">
                    <div>消耗：{{ scope.row['t1ProductionData']['cost'].toFixed(2) }}</div>
                    <div>成本偏差：{{ scope.row['t1ProductionData']['costDeviation'] }}  成本偏差阈值：{{ scope.row['t1ProductionData']['costDeviationValue'] }}</div>
                    <div>实际回传数：{{ scope.row['t1ProductionData']['transitionCount'] }}  最大回传数：{{ scope.row['t1ProductionData']['maxTransitionCount'] }}</div>
                    <div>回收：{{ scope.row['t1ProductionData']['income'].toFixed(2) }}  账面ROI：{{ scope.row['t1ProductionData']['roi'] }}</div>
                    <div>预计赔付：{{ scope.row['t1ProductionData']['compensation'].toFixed(2) }}  赔反ROI：{{ scope.row['t1ProductionData']['compensationRoi'] }}</div>
                    <div>利润（预估）：{{ scope.row['t1ProductionData']['profit'] }}</div>
                  </div>
                  <div v-else>无</div>
                </template>
            </el-table-column>
            <el-table-column label="投放赔付周期T2" align="center" prop="cost" width="250">
                <template #default="scope">
                  <div v-if="scope.row['t2ProductionData']">
                    <div>消耗：{{ scope.row['t2ProductionData']['cost'].toFixed(2) }}</div>
                    <div>成本偏差：{{ scope.row['t2ProductionData']['costDeviation'] }}  成本偏差阈值：{{ scope.row['t2ProductionData']['costDeviationValue'] }}</div>
                    <div>实际回传数：{{ scope.row['t2ProductionData']['transitionCount'] }}  最大回传数：{{ scope.row['t2ProductionData']['maxTransitionCount'] }}</div>
                    <div>回收：{{ scope.row['t2ProductionData']['income'].toFixed(2) }}  账面ROI：{{ scope.row['t2ProductionData']['roi'] }}</div>
                    <div>预计赔付：{{ scope.row['t2ProductionData']['compensation'].toFixed(2) }}  赔反ROI：{{ scope.row['t2ProductionData']['compensationRoi'] }}</div>
                    <div>利润（预估）：{{ scope.row['t2ProductionData']['profit'] }}</div>
                  </div>
                  <div v-else>无</div>
                </template>
            </el-table-column>
            <el-table-column label="arpu分布" align="center" prop="arpuData" width="200" v-if="queryParams.type!=='2'">
                <template #default="scope">
                    <div v-if="scope.row.arpuData && scope.row.arpuData.avg">
                      <div v-if="Array.isArray(scope.row.arpuData.rangeData)" v-for="(item, index) in scope.row.arpuData.rangeData" :key="index">
                        {{ item.incomeRange }}：{{ item.userCount }} ({{ item.incomeRangeRate }}%)
                      </div>
                      <div>平均：{{ scope.row.arpuData.avg }}</div>
                    </div>
                    <div v-else>无</div>
                </template>
            </el-table-column>
            <el-table-column label="ecpm分布" align="center" prop="ecpmData" width="200" v-if="queryParams.type!=='2'">
                <template #default="scope">
                    <div v-if="scope.row.ecpmData && scope.row.ecpmData.ecpmAvg">
                      <div v-if="Array.isArray(scope.row.ecpmData.rangeData)" v-for="(item, index) in scope.row.ecpmData.rangeData" :key="index">
                        {{ item.incomeRange }}：{{ item.userCount }} ({{ item.incomeRangeRate }}%)
                      </div>
                      <div>平均：{{ scope.row.ecpmData.ecpmAvg }}</div>
                    </div>
                    <div v-else>无</div>
                </template>
            </el-table-column>
            <el-table-column label="转化数据" align="center" prop="convertData" width="300" v-if="queryParams.type!=='2'">
                <template #default="scope">
                    <div>展示：{{scope.row['convertData']['impressionNum']}}  cpm：{{ scope.row['convertData']['cpm'] }}</div>
                    <div>点击：{{scope.row['convertData']['clickNum']}}  ({{(scope.row['convertData']['clickRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['clickCost'] }}</div>
                    <div>启动：{{scope.row['convertData']['startNum']}} ({{(scope.row['convertData']['startRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['startCost'] }}</div>
                    <div>广告渗透：{{scope.row['convertData']['showNum']}}  ({{(scope.row['convertData']['showRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['showCost'] }}</div>
                    <div>激活(Z)：{{scope.row['convertData']['activationNum']}}  ({{(scope.row['convertData']['activationRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['activationCost'] }}</div>
                    <div>激活(J)：{{scope.row['convertData']['activationCtNum']}}  ({{(scope.row['convertData']['activationCtRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['activationCtCost'] }}</div>
                    <div>注册(Z)：{{scope.row['convertData']['RegisterNum']}}  ({{(scope.row['convertData']['RegisterRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['RegisterCost'] }}</div>
                    <div>注册(J)：{{scope.row['convertData']['RegisterCtNum']}}  ({{(scope.row['convertData']['RegisterCtRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['RegisterCtCost'] }}</div>
                    <div>付费(Z)：{{scope.row['convertData']['payNum']}}  ({{(scope.row['convertData']['payRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['payCost'] }}</div>
                    <div>付费(J)：{{scope.row['convertData']['payCtNum']}}  ({{(scope.row['convertData']['payCtRate']*100).toFixed(2)}}%)  成本：{{ scope.row['convertData']['payCtCost'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="用户行为" align="center" prop="behaviorData" width="200">
                <template #default="scope">
                    <div>IPU：{{ scope.row['behaviorData']['totalIpu'] }}</div>
                    <div>IPU(除信息流)：{{ scope.row['behaviorData']['ipu'] }}</div>
                    <div>平均启动：{{ scope.row['behaviorData']['startIpuAvgCount'] }}</div>
                    <div>次留：{{ scope.row['behaviorData']['morrowKeepRate'] }}</div>
                </template>
            </el-table-column>
            <el-table-column label="更新时间" align="center" prop="updatetime" width="100" />
            <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" v-if="queryParams.type=='2'" @click="_queryParams('3',scope.row)">查询账户</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='2' || queryParams.type=='3'" @click="_queryParams('4',scope.row)">查询计划</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='2' || queryParams.type=='3' || queryParams.type=='4'" @click="_queryParams('5',scope.row)">查询任务</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='2' || queryParams.type=='3' || queryParams.type=='4' || queryParams.type=='5'" @click="_queryParams('6',scope.row)">查询创意</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='5'" @click="handlePriceList(scope.row)">出价记录</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='5'" @click="handlePassbackConfig(scope.row)">设置成本偏差</el-button>
                  <el-button size="mini" type="text" v-if="queryParams.type=='5'" @click="handlePassBackList(scope.row)">回传补偿</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
        <!-- 修改成本偏差弹框 -->
        <el-dialog :title="'设置成本偏差'" :visible.sync="passbackConfigOpen" width="500px" append-to-body>
            <el-form ref="passbackConfigForm" :model="passbackConfigForm" size="small" label-width="120px" class="dialog-form">
                <el-form-item label="T1成本偏差值" prop="t1CostDeviation">
                  <el-input v-model="passbackConfigForm.t1CostDeviation" placeholder="请输入T1成本偏差值" />
                </el-form-item>
                <el-form-item label="T2成本偏差值" prop="t2CostDeviation">
                  <el-input v-model="passbackConfigForm.t2CostDeviation" placeholder="请输入T2成本偏差值" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="passbackConfigSubmitForm">确 定</el-button>
                <el-button @click="passbackConfigCancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 修改出价弹框 -->
        <el-dialog :title="'修改出价'" :visible.sync="offerOpen" width="500px" append-to-body>
            <el-form ref="offerForm" :model="offerForm" size="small" label-width="120px" class="dialog-form">
                <el-form-item label="今日出价" prop="toDayOperation">
                  <el-tag>{{offerForm.toDayOperation}}</el-tag>
                </el-form-item>
                <el-form-item label="当前出价" prop="beforeOperation">
                  <el-tag>{{offerForm.beforeOperation}}</el-tag>
                </el-form-item>
                <el-form-item label="修改出价倍数" prop="rate">
                  <el-input-number v-model="offerForm.rate" :precision="1" :step="0.1" :min="0.8" :max="1.2" @change="offerChange"></el-input-number>
                </el-form-item>
                <el-form-item label="修改后出价" prop="afterOperation">
                  <el-tag>{{offerForm.afterOperation}}</el-tag>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="offerSubmitForm">确 定</el-button>
                <el-button @click="offerCancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 出价记录列表弹框 -->
        <el-dialog :title="'出价记录列表'" :visible.sync="offerListOpen" width="640px" append-to-body>
          <el-table v-loading="offerListLoading" :data="offerDataList" :height="300" @selection-change="handleSelectionChange">
              <el-table-column label="操作前值" align="center" width="200" prop="beforeOperation"/>
              <el-table-column label="操作后值" align="center" width="200" prop="afterOperation"/>
              <el-table-column label="修改时间" align="center" width="200" prop="createTime"/>
          </el-table>
          <pagination v-show="offerDataTotal > 0" :total="offerDataTotal" :page.sync="offerDataQueryParams.pageNum" :limit.sync="offerDataQueryParams.pageSize"
              @pagination="offerDataList" />
        </el-dialog>
        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="'回传补偿列表'" :visible.sync="open" width="1200" append-to-body>
          <el-form :model="passBackQueryParams" size="mini">
            <el-row>
              <el-col :span="16">
                  <el-query-row :label="'arpu范围'" :labelWidth="80" class="table-button-group">
                      <el-col :span="8">
                          <el-form-item prop="minArpu">
                              <el-input placeholder="最小arpu值" v-model="passBackQueryParams.minArpu" clearable/>
                          </el-form-item>
                      </el-col>
                      <el-col class="line" style="width: 15px;">-</el-col>
                      <el-col :span="8">
                          <el-form-item prop="maxArpu">
                              <el-input placeholder="最大arpu值" v-model="passBackQueryParams.maxArpu" clearable/>
                          </el-form-item>
                      </el-col>
                  </el-query-row>
              </el-col>
              <el-col :span="16">
                  <el-query-row :label="'ecpm范围'" :labelWidth="80" class="table-button-group">
                      <el-col :span="8">
                          <el-form-item prop="minEcpm">
                              <el-input placeholder="最小ecpm值" v-model="passBackQueryParams.minEcpm" clearable/>
                          </el-form-item>
                      </el-col>
                      <el-col class="line" style="width: 15px;">-</el-col>
                      <el-col :span="8">
                          <el-form-item prop="maxEcpm">
                              <el-input placeholder="最大ecpm值" v-model="passBackQueryParams.maxEcpm" clearable/>
                          </el-form-item>
                      </el-col>
                  </el-query-row>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16">
                  <el-query-row :label="'ipu范围'" :labelWidth="80" class="table-button-group">
                      <el-col :span="8">
                          <el-form-item prop="minIpu">
                              <el-input placeholder="最小ipu值" v-model="passBackQueryParams.minIpu" clearable/>
                          </el-form-item>
                      </el-col>
                      <el-col class="line" style="width: 15px;">-</el-col>
                      <el-col :span="8">
                          <el-form-item prop="maxIpu">
                              <el-input placeholder="最大ipu值" v-model="passBackQueryParams.maxIpu" clearable/>
                          </el-form-item>
                      </el-col>
                  </el-query-row>
              </el-col>
              <el-col :span="13">
                <el-form-item :label="'时间范围'" prop="passBackDateRange">
                  <el-date-picker
                  v-model="passBackQueryParams.passBackDateRange"
                  value-format="yyyy-MM-dd"
                  type="datetimerange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-value="[new Date(), new Date()]"
                  :default-time="['00:00:00']"/>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="mb10">
                  <el-form-item>
                      <el-button type="primary" icon="el-icon-search" @click="queryPassBackList">搜索</el-button>
                  </el-form-item>
              </el-col>
              <el-col :span="2" class="mb10">
                  <el-form-item>
                      <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
                  </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table v-loading="passBackLoading" :data="passBackDataList" :height="300" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="监测日期" align="center" width="100" prop="date"/>
              <el-table-column label="监测小时" align="center" width="100" prop="achour"/>
              <el-table-column label="oaId" align="center" width="300" prop="oaId"/>
              <el-table-column label="arpu" align="center" width="100" prop="arpu"/>
              <el-table-column label="ecpm" align="center" width="100" prop="ecpm"/>
              <el-table-column label="ipu" align="center" width="100" prop="ipu"/>
              <el-table-column label="已回传" align="center" width="100">
                 <template slot-scope="scope">
                   <div v-if="scope.row.activation">激活</div>
                   <div v-if="scope.row.register">注册</div>
                   <div v-if="scope.row.pay">付费</div>
                 </template>
              </el-table-column>
          </el-table>
          <pagination v-show="passBackTotal > 0" :total="passBackTotal" :page.sync="passBackQueryParams.pageNum" :limit.sync="passBackQueryParams.pageSize"
              @pagination="queryPassBackList" />
          <div slot="footer" class="dialog-footer">
            <el-row>
              <el-col :span="17">
                <el-checkbox-group v-model="checkEvent">
                  <el-checkbox v-for="event in eventList" :label="event.value" :key="event.value">{{event.name}}</el-checkbox>
                </el-checkbox-group>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="submitForm">确定回传</el-button>
                <el-button @click="cancel">取 消</el-button>
              </el-col>
            </el-row>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import baseTableAdv from '@/mixins/baseTableAdv';
import { computedDate, arrParamToStr, formatTime } from '@/utils/index';
import { getAccountList } from "@/api/place-manage/account";
import { passBackList, batchCompensate } from "@/api/common/compensate";
import { getPlaceList ,listTable ,queryOfferList ,updatePrice ,updatePassbackConfig, huaweiTask } from "@/api/place-report/hwSearch";
export default {
    name: 'Search',
    mixins: [baseTableAdv],
    dicts: ['sys_channel','ACCOUNT_AGENT'],
    data() {
        return {
            // 默认排序
            defaultSort: { prop: 'cost', order: 'descending' },
            eventList:[{name:'激活',value:1},{name:'注册',value:3},{name:'付费',value:4}],
            // 是否显示弹出层
            open: false,
            offerOpen: false,
            offerListOpen: false,
            passbackConfigOpen: false,
            passBackLoading: false,
            offerListLoading: false,
            oppoReportTaskLoading: false,
            passBackDataList:[],
            passBackTotal: 0,
            offerDataList: [],
            offerDataTotal: 0,
            checkEvent: [],
            // 账户
            accountList: [],
            filteredAccountOptions: [],
            // 计划
            placeList: [],
            filteredPlaceOptions: [],
            passBackQueryParams: {
                pageNum: 1,
                pageSize: 10,
                beginDate: '',
                endDate: '',
                minArpu: '',
                maxArpu: '',
                minEcpm: '',
                maxEcpm: '',
                minIpu: '',
                maxIpu: '',
                channel: '',
                pkg: '',
                planId: '',
                adgroupId: '',
            },
            offerDataQueryParams: {
              adgroupId: '',
              type: 2,
              pageNum: 1,
              pageSize: 10,
            },
            pickerOptions: {
              shortcuts: [{
                text: '今天',
                onClick(picker) {
                  const start = new Date();
                  start.setHours(0, 0, 0, 0);
                  const end = new Date();
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              },{
                text: '昨天',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24);
                  start.setHours(0, 0, 0, 0);
                  end.setTime(end.getTime() - 3600 * 1000 * 24);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              },{
                text: '上周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  // 计算上周的周一（自然周以周一开始）
                  start.setDate(start.getDate() - start.getDay() - 6);
                  start.setHours(0, 0, 0, 0);
                  // 计算上周的周日
                  end.setDate(start.getDate() + 6);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '本月',
                onClick(picker) {
                  const now = new Date();
                  const year = now.getFullYear();
                  const month = now.getMonth(); // 0-11
                  const start = new Date(year, month , 1);
                  start.setHours(0, 0, 0, 0);
                  const end = new Date(year, month+1, 0);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '上月',
                onClick(picker) {
                  const now = new Date();
                  const year = now.getFullYear();
                  const month = now.getMonth(); // 0-11
                  const start = new Date(year, month - 1, 1);
                  start.setHours(0, 0, 0, 0);
                  const end = new Date(year, month, 0);
                  end.setHours(23, 59, 59, 999);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
            // 表格数据
            tableDataList: [],
            tableData: {},
            offerForm:{
              toDayOperation: 0,
              beforeOperation: 0,
              rate: 1,
              afterOperation: 0,
            },
            passbackConfigForm:{
              t1CostDeviation: 0,
              t2CostDeviation:0
            },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                type: '5', // 数据维度
                dateRange: [computedDate(new Date()), computedDate(new Date())],
                minCost: '',
                minCostOperator: '',
                maxCost: '',
                maxCostOperator: '',
                minRoi: '',
                minRoiOperator: '',
                maxRoi: '',
                maxRoiOperator: '',
                pkg: '',
                channel: '',
                accountName: '',
                accountId: '',
                agentCode: '',
                scheme: '',
            },
            // 数据维度
            dataDimensionList: [
              // { name: '渠道', value: '1' },
              // { name: '应用', value: '2' },
              // { name: '账户', value: '3' },
              // { name: '计划', value: '4' },
              { name: '任务', value: '5' },
              // { name: '创意', value: '6' },
              ],
            // Symbol
            indexSymbol: [{ name: "大于等于", val: "1" }, { name: "小于等于", val: "2" }, { name: "等于", val: "3" }, { name: "大于", val: "4" }, { name: "小于", val: "5" }],
            currRowIndex: null
        }
    },
    created() {
        this._getProductList();
        this._getAccountList();
        this._getPlaceList();
        this._integrationParams();
        this.getList();
    },
    mounted() {
      if (this.$route.query.type) this.queryParams.type = this.$route.query.type;
    },
    methods: {
      reportTask(){
        this.reportTaskLoading = true;
        let acDate = this.queryParams.dateRange[0];
        acDate = acDate.substring(0,10);
        let param = {'startDate':acDate,'endDate': acDate};
        huaweiTask(arrParamToStr({ ...param })).then(response => {
          if(response.code==200){
            this.getList();
            this.$modal.msgSuccess("执行成功");
          }else{
            this.$modal.msgError("执行失败");
          }
        }).finally(() => {
          this.reportTaskLoading = false;
        });
      },
        accountFilter(query) {
            if (!query) {
              this.filteredAccountOptions = this.accountList;
              return;
            }
            const keyword = query.toLowerCase();
            this.filteredAccountOptions = this.accountList.filter(item =>
              item.accountId.toLowerCase().includes(keyword) ||
              item.accountName.toLowerCase().includes(keyword)
            )
        },
        placeFilter(query) {
            if (!query) {
              this.filteredPlaceOptions = this.placeList;
              return;
            }
            const keyword = query.toLowerCase();
            this.filteredPlaceOptions = this.placeList.filter(item =>
              item.dimensionId.toLowerCase().includes(keyword) ||
              item.dimensionName.toLowerCase().includes(keyword)
            )
        },
        // 获取账户列表
        _getAccountList () {
          let param = {"channel":"huawei"}
          getAccountList(param).then(response => {
            this.accountList = response.data
            this.filteredAccountOptions = response.data
          })
        },
        _getPlaceList() {
          getPlaceList({type: this.queryParams.type}).then(response => {
            this.placeList = response.data;
            this.filteredPlaceOptions = response.data;
          })
        },
        _changeParams(key, value) {
            let vm = this
            vm.queryParams[key] = value
            if(vm.queryParams["type"]!=='2'){
              vm._getPlaceList()
            }
            vm.handleQuery()
        },
        _queryParams(type,row) {
            let vm = this
            vm.queryParams.type = type
            vm.queryParams.pkg = row.pkg
            if(vm.queryParams["type"]!=='2'){
              vm._getPlaceList()
            }
            vm.handleQuery()
        },
        // 修改出价弹框
        handleOffer(row){
          let vm = this;
          vm.offerOpen = true;
          vm.offerForm.type = 2;
          vm.offerForm.adgroupId = row.adgroupId;
          let param = {"adgroupId":row.adgroupId,"type":1,"params":{"beginTime":computedDate(new Date())+' 00:00:00',"endTime":computedDate(new Date())+' 23:59:59'}};
          queryOfferList(param).then(response => {
                vm.offerForm.toDayOperation = parseFloat(response.rows[0].beforeOperation);
                vm.offerForm.beforeOperation = row.offer;
                vm.offerForm.rate = vm.offerForm.beforeOperation/vm.offerForm.toDayOperation;
                vm.offerForm.afterOperation = vm.offerForm.toDayOperation*vm.offerForm.rate;
          });
        },
        offerChange(value){
          let vm = this;
          vm.offerForm.afterOperation = (vm.offerForm.toDayOperation*value).toFixed(2);
        },
        offerCancel(){
          let vm = this;
          vm.offerOpen = false;
          vm.offerForm = {};
        },
        offerSubmitForm(){
          let vm = this;
          updatePrice(vm.offerForm).then(response => {
            vm.offerOpen = false;
            vm.offerForm = {};
            this.getList();
            this.$modal.msgSuccess("修改成功");
          });
        },
        handlePassbackConfig(row){
          let vm = this;
          vm.passbackConfigOpen = true;
          vm.passbackConfigForm.adgroupId = row.adgroupId;
          vm.passbackConfigForm.t1CostDeviation = row.t1ProductionData.costDeviationValue;
          vm.passbackConfigForm.t2CostDeviation = row.t2ProductionData.costDeviationValue;
        },
        passbackConfigSubmitForm(){
          let vm = this;
          updatePassbackConfig(vm.passbackConfigForm).then(response => {
            vm.passbackConfigOpen = false;
            this.getList();
            this.$modal.msgSuccess("修改成功");
          });
        },
        passbackConfigCancel(){
          let vm = this;
          vm.passbackConfigOpen = false;
          vm.passbackConfigForm = {};
        },
        /** 查询ROI数据列表 */
        getList() {
            let vm = this;
            vm.loading = true;
            listTable(arrParamToStr({ ...vm.queryParams })).then(response => {
                vm.tableDataList = response.rows.map(item => {
                    item.status = item.status;
                    item.updatetime = formatTime(item.updatetime);
                    // item.updatetime = item.updatetime;
                    item.totalProductionData = JSON.parse(item.totalProductionData);
                    item.t1ProductionData = JSON.parse(item.t1ProductionData);
                    item.t2ProductionData = JSON.parse(item.t2ProductionData);
                    item.arpuData = JSON.parse(item.arpuData);
                    item.ecpmData = JSON.parse(item.ecpmData);
                    item.convertData = JSON.parse(item.convertData);
                    item.behaviorData = JSON.parse(item.behaviorData);
                    return item;
                });
                vm.tableData = response.totalData;
                vm.total = response.total;
                vm.loading = false;
            }).catch(error => {
                vm.loading = false;
                console.log(error);
            });
        },
        handlePriceList(row){
          let vm = this;
        },
        handlePassBackList(row){
          let vm = this;
          vm.open = true;
          vm.passBackQueryParams.channel = row.channel;
          vm.passBackQueryParams.pkg = row.pkg;
          vm.passBackQueryParams.adgroupId = row.adgroupId;
          vm.passBackQueryParams.beginDate = row.acdate;
          vm.passBackQueryParams.endDate = row.acdate;
          vm.queryPassBackList();
        },
        queryPassBackList(){
          let vm = this;
          vm.passBackLoading = true;
          console.log(vm.passBackQueryParams);
          if(vm.passBackQueryParams.passBackDateRange){
            vm.passBackQueryParams.beginDate = vm.passBackQueryParams.passBackDateRange[0]
            vm.passBackQueryParams.endDate = vm.passBackQueryParams.passBackDateRange[1]
          }
          passBackList(arrParamToStr({ ...vm.passBackQueryParams })).then(response => {
                vm.passBackDataList = response.rows;
                vm.passBackTotal = response.total;
                vm.passBackLoading = false;
            }).catch(error => {
                vm.passBackLoading = false;
                console.log(error);
            });
        },
        handlePriceList(row){
          let vm = this;
          vm.offerListOpen = true;
          vm.offerListLoading = true;
          vm.offerDataQueryParams.adgroupId=row.adgroupId;
          queryOfferList(arrParamToStr({ ...vm.offerDataQueryParams })).then(response => {
              vm.offerDataList = response.rows;
              vm.offerDataTotal = response.total;
              vm.offerListLoading = false;
            }).catch(error => {
                vm.offerListLoading = false;
            });

        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.oaids = selection.map(item => item.oaId)
          this.single = selection.length!=1
          this.multiple = !selection.length
        },
        submitForm(){
            let vm = this;
            const params = [];
            if (vm.oaids.length > 0 && vm.checkEvent.length > 0) {
              for (const oaid of this.oaids) {
                for (const type of this.checkEvent) {
                    params.push({"oaid":oaid,"type":type,"channel":vm.passBackQueryParams.channel,"pkg":vm.passBackQueryParams.pkg});
                }
              }
            }
            batchCompensate(params).then(response => {
              if(response.code==200){
                this.$modal.msgSuccess("回传成功");
              }else{
                this.$modal.msgSuccess(response.msg);
              }
            }).catch(error => {
                console.log(error);
            });
        },
        // 取消按钮
        cancel() {
          this.open = false;
          reset()
        },
        reset(){
          let vm = this;
          vm.passBackQueryParams.passBackDateRange = [computedDate(new Date()), computedDate(new Date())];
          vm.passBackQueryParams.minArpu = '';
          vm.passBackQueryParams.maxArpu = '';
          vm.passBackQueryParams.minEcpm = '';
          vm.passBackQueryParams.maxEcpm = '';
          vm.passBackQueryParams.minIpu = '';
          vm.passBackQueryParams.maxIpu = '';
          vm.queryPassBackList()
        }
    }
}
</script>
<style lang="scss" scoped>
.top-total {
    margin-bottom: 20px;
    width: 100%;
    display: flex;
    .item {
        margin-right: 20px;
        padding: 20px;
        width: 200px;
        border: #333 1px solid;
        border-radius: 5px;
        color: #333;
        h3 {
            margin: 0 0 10px;
            font-size: 18px;
            font-weight: bold;
        }
        p {
            margin: 0px;
            font-size: 14px;
            font-weight: bold;
        }
    }
}
</style>
